package com.ruoyi.fun.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.common.utils.SecurityUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

/**
 * 移动端Token检测Controller
 * 
 * @author ruoyi
 * @date 2025-01-17
 */
@RestController
@RequestMapping("/mobile/token")
public class EcMobileTokenController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(EcMobileTokenController.class);
    
    @Autowired
    private TokenService tokenService;
    
    @Autowired
    private RedisCache redisCache;
    
    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    /**
     * 检测Token是否有效
     * 需要在请求头中携带Authorization: Bearer {token}
     */
    @GetMapping("/check")
    public AjaxResult checkToken()
    {
        try {
            // 尝试获取当前登录用户信息
            LoginUser loginUser = getLoginUser();
            
            if (loginUser != null && loginUser.getUser() != null) {
                // Token有效，返回基本用户信息
                return AjaxResult.success("Token有效", loginUser.getUser().getUserId());
            } else {
                // Token无效
                return AjaxResult.error(401, "Token无效或已过期");
            }
        } catch (Exception e) {
            // Token验证失败
            return AjaxResult.error(401, "Token验证失败: " + e.getMessage());
        }
    }
    
    /**
     * 匿名接口 - 检测Token状态（不需要认证）
     * 通过请求参数传递token进行检测
     */
    @Anonymous
    @GetMapping("/validate")
    public AjaxResult validateToken(String token)
    {
        try {
            if (token == null || token.trim().isEmpty()) {
                return AjaxResult.error(400, "Token不能为空");
            }
            
            // 验证Token格式和有效性
            LoginUser loginUser = getLoginUserByToken(token);
            
            if (loginUser != null && loginUser.getUser() != null) {
                // Token有效
                return AjaxResult.success("Token有效", loginUser.getUser().getUserId());
            } else {
                // Token无效
                return AjaxResult.error(401, "Token无效或已过期");
            }
        } catch (Exception e) {
            // Token验证失败
            return AjaxResult.error(401, "Token验证失败: " + e.getMessage());
        }
    }
    
    /**
     * 通过token字符串获取LoginUser
     * @param token JWT token字符串
     * @return LoginUser对象
     */
    private LoginUser getLoginUserByToken(String token) {
        try {
            // 解析JWT token获取claims
            Claims claims = parseToken(token);
            // 获取用户唯一标识
            String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
            if (uuid != null) {
                // 从Redis缓存中获取用户信息
                String userKey = CacheConstants.LOGIN_TOKEN_KEY + uuid;
                return redisCache.getCacheObject(userKey);
            }
        } catch (Exception e) {
            log.error("解析token失败: {}", e.getMessage());
        }
        return null;
    }
    
    /**
     * 解析JWT token
     * @param token JWT token字符串
     * @return Claims对象
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }
}